<template>
  <hx-page>
    <div class='pay'>
      <div class='pay_header'>
        <uni-segmented-control :values="['待缴费', '已缴费']" activeColor="#b71120" @clickItem="changeTab"
                               :current="current"/>
      </div>
      <div class='pay_scroll'>
        <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" :up="upOption" @up="getList">
          <div class='pay_list'>
            <div v-for="(item,index) in payList" :key="index" class='pay_list_item'>
              <div class='pay_list_item_header'>
                <div class='pay_list_item_header_name'>
                  {{ item.chargeItemName }}
                </div>
                {{ item.chargeItemDesc }}
              </div>
              <div v-if=" current === 0"
                   class='pay_list_item_con'>
                截止时间：{{ timePipe(item.chargeEndDate) }}
              </div>
              <div v-else
                   class='pay_list_item_con'>
                缴费时间：{{ timePipe(item.chargeTime) }}
              </div>
              <div
                  v-if="item.cardBalance > 0"
                  class='pay_list_item_con'>
                卡余额：
                <div
                    class='hxPage_money'>{{ Number(item.cardBalance).toFixed(2) }}
                </div>
                元 (可用于抵扣缴费)
              </div>
              <div
                  v-if="item.cardBalance > 0"
                  class='pay_list_item_con'>
                抵扣金额：
                <input
                    class='hxPage_money_input'
                    name='money'
                    type='number'
                    v-model="item.money"/>
                元
              </div>

              <div class='pay_list_item_footer'>
                <div class='pay_list_item_footer_amount'>
                  {{ item.amount.toFixed(2) }}元
                </div>
                <button
                    v-if="current === 0"
                    class='pay_list_item_footer_button'
                    @click="pay(item)">
                  缴费
                </button>
              </div>
            </div>
          </div>
        </mescroll-body>
      </div>
    </div>
  </hx-page>
</template>

<script>
import {HxLogin, HxPost} from "../../../service/http";
import {hxParam} from "../../../config/hx-param";
import {getFormatDate, timePipe} from "../../../utils/utils";
import MescrollMixin from "../../../uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins";

export default {
  mixins: [MescrollMixin], // 使用mixin
  data() {
    return {
      cardId: '',
      current: 0,
      chargeAppId: '',
      payList: [],
      pageNo: 1,
      pageSize: 10,
      startDate: '20190101',
      endDate: getFormatDate(new Date(), 'yyyyMMdd')
    };
  },
  onShow() {
    this.cardId = hxParam.cardId;
    if (this.cardId) {
      this.current = 0;
      this.changeTab();
    } else {
      uni.switchTab({url: '/pages/personCenter/index'})
          .then(() => {
            uni.showToast({
              title: '请先绑定卡片',
              icon: 'none',
              duration: 3 * 1000
            });
          }).catch();
    }
  },
  methods: {
    timePipe,
    changeTab() {
      this.getListInit();
    },

    getList() {
      this.hasMore = false;
      uni.showLoading({title: '加载中...', mask: true})
          .then(() => {
            return HxLogin();
          })
          .then(() => {
            let param = {
              pageNo: this.pageNo,
              pageSize: this.pageSize,
              startDate: this.startDate,
              endDate: this.endDate
            };
            return HxPost(this.current === 0 ? 'unPayList' : 'hasPayList', param);
          })
          .then((res) => {
            uni.hideLoading();
            if (res['chargeAppId']) {
              this.chargeAppId = res['chargeAppId']
            }
            this.mescroll.endSuccess(res['listSize'] || 0);
            if (res['unChargeList'] || res['chargedList']) {
              this.payList = this.payList.concat(res['unChargeList'] || res['chargedList'])
            } else {
              uni.showToast({title: '无更多记录', icon: 'none', duration: 2 * 1000}).catch();
            }
          })
          .catch((err) => {
            this.mescroll.endErr();
            uni.hideLoading();
            uni.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
          });
    },

    getListInit() {
      this.payList = []
      this.mescroll.scrollTo(0, 0);
      this.mescroll.triggerDownScroll();
    },

    pay(e) {
      console.log(e)
      if (e.payChn === 'WX') {
        HxPay.wxPayAll(e.chargeId)
            .then(() => {
              return uni.showModal({
                title: '',
                content: '缴费完成后，请查看“已缴费”记录',
                showCancel: false,
                confirmText: '确定'
              });
            })
            .then(() => {
              HxPost('payNum', {})
                  .then((res) => {
                    uni.$emit('payNum', {
                      index: 2,
                      text: res['unChargeCnt'] ? res['unChargeCnt'] + '' : ''
                    });
                  });
              return this.getListInit();
            })
            .catch((err) => {
              console.log(err)
              switch (err.errMsg) {
                case 'requestPayment:fail cancel':
                case 'navigateToMiniProgram:fail cancel':
                  err = {retMsg: '取消支付'};
                  break;
              }
              uni.hideLoading();
              uni.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
            });
      } else {
        this.abcPay(e)
      }
    },

    abcPay(e) {
      uni.navigateToMiniProgram({
        appId: this.chargeAppId,
        path: e.chargePayUrl,
      })
          .then(() => {
            return uni.showModal({
              title: '',
              content: '缴费完成后，请查看“已缴费”记录',
              showCancel: false,
              confirmText: '确定'
            });
          })
          .then(() => {
            HxPost('payNum', {})
                .then((res) => {
                  uni.$emit('payNum', {
                    index: 2,
                    text: res['unChargeCnt'] ? res['unChargeCnt'] + '' : ''
                  });
                });
            return this.getListInit();
          })
          .catch((err) => {
            switch (err.errMsg) {
              case 'requestPayment:fail cancel':
              case 'navigateToMiniProgram:fail cancel':
                err = {retMsg: '取消支付'};
                break;
            }
            uni.hideLoading();
            uni.showToast({title: err.retMsg || '未知错误', icon: 'none', duration: 2 * 1000}).catch();
          });
    },

    changeMoney(e) {
      console.log(e)
    },
  }
};
</script>

<style lang="scss" scoped>
.pay {
  &_header {
    margin: 0 20PX;
  }

  &_scroll {
    margin-top: 20PX;
    height: 100%;
    display: flex;
  }

  &_list {
    background: #FFF;
    border-bottom: 1PX solid #e1e1e1;

    &_item {
      display: flex;
      flex-direction: column;
      border-bottom: 1PX solid #e1e1e1;
      padding: 8PX 15PX;
      font-size: 14PX;

      &_header {
        padding-bottom: 5PX;

        &_name {
          font-weight: 700;
          color: #000;
          display: inline-block;
          padding-right: 20PX;
        }
      }

      &_con {
        display: flex;
        padding-bottom: 5PX;
      }

      &_footer {
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        &_amount {
          display: flex;
          align-items: center;
          color: #b71120;
        }

        &_button {
          color: white;
          border-color: #DADADA;
          background: #b71120;
          width: 100%;
          height: 26PX;
          line-height: 26PX;
        }
      }
    }
  }
}
</style>
